const bcosutils = require('./bcosutils');
const bcostars = require('./bcosutils').bcostars;
const TxUtils = require('./bcosutils').TxUtils;
const DataUtils = require('./bcosutils').DataUtils;
/*依赖于bcosutils,封装出主要接口build_raw_tx,减少重复代码而已*/
console.log('bcosutils in test', bcosutils);
var privkey = global.privateKey;

function make_tx_data(blocklimit, to_address, function_data ) {
  var txData = new bcostars.TransactionData();
  txData.version = 1;
  txData.chainID = global.chainId;
  txData.groupID = global.groupId;
  TxUtils.set_txdata_input(txData, function_data);
  var input = DataUtils.arrayToHex(DataUtils.bufferToBytes(txData.input));
  txData.to = to_address;
  txData.blockLimit = blocklimit;
  txData.nonce = DataUtils.bigIntRandom().toString(); //nonce是一个整形数的字符串
  return txData;
}

function sign_raw_tx(txData) {
  var rawtxbin = TxUtils.build_rawtransaction_by_txdata(txData, privkey);
  var rawtxhex = DataUtils.arrayToHex(rawtxbin);
  return rawtxhex;
}

exports.build_raw_tx = function (blocklimit, to_address, function_data) {
  var txData = make_tx_data(blocklimit, to_address, function_data);
  var rawtxhex = sign_raw_tx(txData);
  return rawtxhex;
};
